<!doctype html>
{% load i18n %}
<html lang="{{ LANGUAGE_CODE }}">
  <head>
    {% block title %}<title>{% translate "Local Library" %}</title>{% endblock %}
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    {% load static %}
    {% load compress %}
    <link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>

    <!-- Add additional CSS in static file -->
    {% compress css %}
    <link rel="stylesheet" href="{% static 'css/styles.css' %}" />
    <style>
      :root {
        --primary-color: #2c3e50;
        --secondary-color: #34495e;
        --accent-color: #3498db;
        --text-color: #2c3e50;
        --light-bg: #f8f9fa;
        --border-color: #dee2e6;
      }

      html {
        background-color: white;
        min-height: 100vh;
      }

      body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        color: var(--text-color);
        line-height: 1.6;
        background: transparent;
      }

      .sidebar {
        background-color: var(--primary-color);
        color: white;
        padding: 2rem 1rem;
        height: 100vh;
        position: fixed;
        box-shadow: 2px 0 5px rgba(0,0,0,0.1);
      }

      .sidebar .nav-link {
        color: rgba(255,255,255,0.8);
        padding: 0.8rem 1rem;
        margin: 0.2rem 0;
        border-radius: 5px;
        transition: all 0.3s ease;
      }

      .sidebar .nav-link:hover {
        background-color: var(--accent-color);
        color: white;
        transform: translateX(5px);
      }

      .sidebar .nav-link.active {
        background-color: var(--accent-color);
        color: white;
      }

      .main-content {
        background-color: var(--light-bg);
        min-height: 100vh;
        padding: 2rem;
        margin-left: 16.666667%;
      }

      .card {
        border: none;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: transform 0.3s ease;
      }

      .card:hover {
        transform: translateY(-5px);
      }

      .btn {
        border-radius: 5px;
        padding: 0.5rem 1.5rem;
        transition: all 0.3s ease;
      }

      .btn-primary {
        background-color: var(--accent-color);
        border-color: var(--accent-color);
      }

      .btn-primary:hover {
        background-color: #2980b9;
        border-color: #2980b9;
        transform: translateY(-2px);
      }

      .navbar {
        background-color: white;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        padding: 1rem 2rem;
      }

      .navbar-brand {
        color: var(--primary-color);
        font-weight: bold;
        font-size: 1.5rem;
      }

      .form-control {
        border-radius: 5px;
        border: 1px solid var(--border-color);
        padding: 0.8rem;
      }

      .form-control:focus {
        border-color: var(--accent-color);
        box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
      }

      .pagination {
        margin-top: 2rem;
      }

      .pagination .page-link {
        color: var(--accent-color);
        border: none;
        margin: 0 0.2rem;
        border-radius: 5px;
      }

      .pagination .page-item.active .page-link {
        background-color: var(--accent-color);
        color: white;
      }

      .alert {
        border-radius: 5px;
        border: none;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      }

      .table {
        background-color: white;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      }

      .table thead th {
        background-color: var(--primary-color);
        color: white;
        border: none;
      }

      .table td, .table th {
        padding: 1rem;
        vertical-align: middle;
      }

      .badge {
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-weight: normal;
      }

      .text-muted {
        color: #6c757d !important;
      }

      .container-fluid {
        padding: 0;
      }

      .row {
        margin: 0;
      }

      .user-info-section {
        text-align: center;
        margin-bottom: 2rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
      }

      .user-avatar {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        object-fit: cover;
        margin-bottom: 0.5rem;
        border: 2px solid white;
      }

      .default-avatar {
        font-size: 4rem;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 0.5rem;
      }

      .username {
        color: white;
        font-weight: bold;
        font-size: 1.1rem;
      }

      @media (max-width: 768px) {
        .sidebar {
          position: static;
          height: auto;
        }
        .main-content {
          margin-left: 0;
        }
      }

      /* Profile Editor Sidebar Styles */
      .profile-editor-sidebar {
        position: fixed;
        top: 0;
        right: 0;
        width: 400px; /* Adjust width as needed */
        height: 100%;
        background-color: white;
        box-shadow: -5px 0 15px rgba(0,0,0,0.2);
        transform: translateX(100%); /* Initially hidden off-screen to the right */
        transition: transform 0.3s ease-in-out;
        z-index: 1050;
        overflow-y: auto;
        padding: 20px;
      }

      .profile-editor-sidebar.show {
        transform: translateX(0); /* Slide into view */
      }

      .profile-editor-sidebar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 10px;
      }

      .profile-editor-sidebar-close {
        background: none;
        border: none;
        font-size: 1.5rem;
        cursor: pointer;
        color: var(--text-color);
      }

      .overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1040;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s ease-in-out;
      }

      .overlay.show {
        opacity: 1;
        visibility: visible;
      }
    </style>
    {% endcompress %}
  </head>

  <body>
    {% if messages %}
      <div class="container mt-2">
        {% for message in messages %}
          <div class="alert alert-{{ message.tags }}">{{ message }}</div>
        {% endfor %}
      </div>
    {% endif %}
    <div class="language-selector">
      <form action="{% url 'set_language' %}" method="post">
        {% csrf_token %}
        {% get_current_language as CURRENT_LANGUAGE %}
        <select name="language" onchange="this.form.submit()" class="form-select">
          <option value="en" {% if CURRENT_LANGUAGE == 'en' %}selected{% endif %}>{% trans "English" %} (en)</option>
          <option value="zh-hans" {% if CURRENT_LANGUAGE == 'zh-hans' %}selected{% endif %}>{% trans "简体中文" %} (zh-hans)</option>
        </select>
      </form>
    </div>
    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-2 sidebar">
          <div class="d-flex flex-column">
            <a href="{% url 'home' %}" class="navbar-brand mb-4">LYF Library</a>
            {% if user.is_authenticated %}
            <div class="user-info-section">
                {% if user.profile.avatar %}
                    <img src="{{ user.profile.avatar.url }}" alt="User Avatar" class="user-avatar">
                {% else %}
                    <i class="fas fa-user-circle default-avatar"></i>
                {% endif %}
                <div class="username">{{ user.username }}</div>
            </div>
            {% endif %}
            <ul class="nav flex-column">
              <li class="nav-item">
                <a class="nav-link {% if request.path == '/' %}active{% endif %}" href="{% url 'home' %}">
                  <i class="fas fa-home"></i> {% trans "Home" %}
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link {% if 'books' in request.path %}active{% endif %}" href="{% url 'catalog:books' %}">
                  <i class="fas fa-book"></i> {% trans "All Books" %}
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link {% if 'authors' in request.path %}active{% endif %}" href="{% url 'catalog:authors' %}">
                  <i class="fas fa-user"></i> {% trans "All Authors" %}
                </a>
              </li>
              {% if user.is_authenticated %}
              <li class="nav-item">
                <a class="nav-link {% if 'my-borrowed' in request.path %}active{% endif %}" href="{% url 'catalog:my-borrowed' %}">
                  <i class="fas fa-bookmark"></i> {% trans "My Borrowed" %}
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link {% if 'my-favorites' in request.path %}active{% endif %}" href="{% url 'catalog:my-favorites' %}">
                  <i class="fas fa-heart"></i> {% trans "My Favorites" %}
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#" id="edit-profile-btn">
                  <i class="fas fa-user-edit"></i> {% trans "Edit Profile" %}
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="{% url 'catalog:ai_chat' %}">{% translate "AI Chat" %}</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="{% url 'catalog:book_statistics' %}">{% translate "Book Statistics" %}</a>
              </li>
              {% endif %}
              {% if perms.catalog.can_mark_returned %}
              <li class="nav-item">
                <a class="nav-link {% if 'all-borrowed' in request.path %}active{% endif %}" href="{% url 'catalog:all-borrowed' %}">
                  <i class="fas fa-list"></i> {% trans "All Borrowed" %}
                </a>
              </li>
              {% endif %}
            </ul>
          </div>
        </div>
        <div class="col-sm-10 main-content">
          <nav class="navbar navbar-expand-lg">
            <div class="container-fluid">
              <div class="d-flex align-items-center">
                {% if user.is_authenticated %}
                <span class="me-3">{% translate "Welcome," %} {{ user.get_username }}</span>
                <li class="nav-item">
                    <form action="{% url 'logout' %}" method="post">
                        {% csrf_token %}
                        <input type="hidden" name="next" value="/" />
                        <button type="submit" class="btn btn-danger btn-sm">{% translate "Logout" %}</button>
                    </form>
                </li>
                {% else %}
                <a href="{% url 'login' %}?next={{ request.path }}" class="btn btn-outline-primary">{% translate "Login" %}</a>
                {% endif %}
              </div>
            </div>
          </nav>

          {% if messages %}
          <div class="messages">
            {% for message in messages %}
            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
              {{ message }}
              <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endfor %}
          </div>
          {% endif %}

          {% block content %}{% endblock %}
          {% block pagination %}
            {%if is_paginated %}
                <div class="pagination">
                    <span class="page-links">
                        {% if page_obj.has_previous %}
                            <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">{% trans "previous" %}</a>
                        {% endif %}
                        <span class="page-current">
                            {% trans "Page" %} {{ page_obj.number }} {% trans "of" %} {{ page_obj.paginator.num_pages }}.
                        </span>
                        {% if page_obj.has_next %}
                            <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">{% trans "next" %}</a>
                        {% endif %}
                    </span>
                </div>
            {% endif %}
          {% endblock %}
        </div>
      </div>
    </div>

    <!-- Profile Editor Sidebar -->
    <div class="profile-editor-sidebar" id="profile-editor-sidebar">
      <div class="profile-editor-sidebar-header">
        <h3>Edit Profile</h3>
        <button class="profile-editor-sidebar-close">&times;</button>
      </div>
      <div id="profile-editor-content">
        <!-- Profile form will be loaded here -->
        Loading profile...
      </div>
    </div>

    <!-- Overlay for when sidebar is open -->
    <div class="overlay" id="overlay"></div>

    <!-- 已移除重复的Bootstrap JS引用 -->
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        const editProfileBtn = document.getElementById('edit-profile-btn');
        const profileEditorSidebar = document.getElementById('profile-editor-sidebar');
        const profileEditorContent = document.getElementById('profile-editor-content');
        const closeBtn = document.querySelector('.profile-editor-sidebar-close');
        const overlay = document.getElementById('overlay');

        if (editProfileBtn) {
          editProfileBtn.addEventListener('click', function(e) {
            e.preventDefault();
            openProfileEditor();
          });
        }

        if (closeBtn) {
          closeBtn.addEventListener('click', closeProfileEditor);
        }

        if (overlay) {
          overlay.addEventListener('click', closeProfileEditor);
        }

        function openProfileEditor() {
          profileEditorSidebar.classList.add('show');
          overlay.classList.add('show');
          // Load content from the profile_edit URL
          fetch('{% url "catalog:profile_edit" %}', {
            headers: {
              'X-Requested-With': 'XMLHttpRequest'
            }
          })
            .then(response => response.text())
            .then(html => {
              const parser = new DOMParser();
              const doc = parser.parseFromString(html, 'text/html');
              // Extract the content block from the fetched page
              const content = doc.querySelector('.container.mt-4').innerHTML;
              profileEditorContent.innerHTML = content;
              attachFormSubmitHandler();
            })
            .catch(error => console.error('Error loading profile edit page:', error));
        }

        function closeProfileEditor() {
          profileEditorSidebar.classList.remove('show');
          overlay.classList.remove('show');
        }

        function attachFormSubmitHandler() {
          const profileForm = profileEditorContent.querySelector('form');
          if (profileForm) {
            profileForm.addEventListener('submit', function(e) {
              e.preventDefault();
              const formData = new FormData(profileForm);

              fetch(profileForm.action, {
                method: 'POST',
                body: formData
              })
              .then(response => response.text())
              .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const content = doc.querySelector('.container.mt-4').innerHTML; // Re-load content in case of validation errors
                profileEditorContent.innerHTML = content;
                attachFormSubmitHandler(); // Re-attach handler for new form
                // Check for success message from Django messages framework
                const messagesDiv = doc.querySelector('.messages');
                if (messagesDiv) {
                  // For demonstration, just log or display to user in a more integrated way
                  console.log('Messages:', messagesDiv.textContent);
                  // You might want to append these messages to a global message area
                  // or refresh the page to show Django messages.
                }
                // If there are no form errors, close the sidebar
                if (!doc.querySelector('.errorlist')) {
                  closeProfileEditor();
                  // Optionally, refresh the whole page or update user info on sidebar
                  location.reload(); // Simple full page reload to show changes
                }
              })
              .catch(error => console.error('Error submitting profile form:', error));
            });
          }
        }
      });
    </script>
    {% block extra_js %}{% endblock %}
  </body>
</html>
